<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_allinpay/model')->方法名();
	https://aipboss.allinpay.com/know/devhelp/main.php?pid=38
	https://isv-test.allinpay.com/project/29/
*/
namespace jy_allinpay;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function unionorder($params=array()){
		$basic=$this->plugin_setting('basic');
		if($basic['istest']){
			if($params['paytype']=='wechat' || $params['paytype']=='alipay'){
				$api_url='https://syb-test.allinpay.com/apiweb/h5unionpay/unionorder';
			}elseif($params['paytype']=='union_online'){
				$api_url='https://syb-test.allinpay.com/apiweb/qpay/payapplyagree';
			}else{
				$api_url='https://syb-test.allinpay.com/apiweb/qpay/payapplyagree';
			}
		}else{
			if($params['paytype']=='wechat' || $params['paytype']=='alipay'){
				$api_url='https://syb.allinpay.com/apiweb/h5unionpay/unionorder';
			}elseif($params['paytype']=='union_online'){
				$api_url='https://syb-test.allinpay.com/apiweb/qpay/payapplyagree';
			}else{
				$api_url='https://vsp.allinpay.com/apiweb/qpay/payapplyagree';
			}
		}
		$_SESSION['returl']=$params['return_url'];
		$params['remark']=$_SERVER['HTTP_HOST'];
		if($params['paytype']=='wechat' || $params['paytype']=='alipay'){
			$post = array(
				'remark'=>$params['remark']?:$params['title'],
				'reqsn'=>$params['tid'],
				'trxamt'=>intval($params['fee']*100).'',
				'returl'=>custom_url($params['success_url'],true),
				'notify_url'=>SITEROOT .'addons/jy_allinpay/notify.php',
			);
		}elseif($params['paytype']=='union_online'){
			$qianyue=pdo_get('jy_allinpay_log',array('passed'=>1,'uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']));
			if(!$qianyue['agreeid']){
				exi('','','jy_allinpay/index//tid='.$params['tid']);
			}
			$params['agreeid']=$qianyue['agreeid'];
			$this->payapplyagree($params);
		}
		$res=$this->request($api_url,$post,$params);
		return $res;
		exi('支付参数设置错误！','error');
	}
	public function request($url='',$post=array(),$params=array()){
		$merchid=$params['merchid'];
		$iswxapp=$params['iswxapp'];
		$setting=uni_setting('pay');
		if($merchid){
			$jy_merch=cfc('core')->plugin_exists('jy_merch');
			$jy_merch=plugin('jy_merch')->plugin_setting('setting');
			if($jy_merch['isone_allinpay']){
				$merchset=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'setting');
				$merchset=json_decode($merchset,true);
				if($merchset['allinpay']){
					$setting=$merchset;
				}
			}
		}
		$private_key=$setting['allinpay_rsakey'];
		if(!$setting['allinpay_appid'] || !$setting['allinpay_cusid']|| !$setting['allinpay_rsakey']){
			exi('请前往：支付参数--通联支付填写：接口参数！','error');
		}
		$post['orgid']=$setting['allinpay_orgid']?:'';
		$post['cusid']=$setting['allinpay_cusid'];
		$post['appid']=$setting['allinpay_appid'];
		$post['randomstr']=random(32);
		/*if($_SESSION['container']='wechat'){
			$wechatappid=pdo_getcolumn('core_account_wechat',array('id'=>$_SESSION['wechat_id'],'uniacid'=>$_SESSION['uniacid']),'appid');
			$post['sub_appid']=$wechatappid;
		}*/
		if($iswxapp){
			$fields=array('cusid','appid','orgid','trxamt','reqsn','notify_url','remark','randomstr');
			$extraData=array_fields($fields,$post);
			$extraData['version']='12';
			$extraData['limit_pay']='no_credit';
			$extraData['paytype']='W06';
			$extraData['validtime']='15';
			$extraData['signtype']='RSA';
			$sign=$this->sign($extraData,$setting['allinpay_rsakey']);
			$extraData['sign']=$sign;
			return $extraData;
		}elseif($params['paytype']=='alipay'){
			$fields=array('cusid','appid','orgid','trxamt','reqsn','notify_url','remark','randomstr');
			$extraData=array_fields($fields,$post);
			$extraData['version']='12';
			$extraData['limit_pay']='no_credit';
			$extraData['paytype']='A02';
			$extraData['validtime']='15';
			$extraData['signtype']='RSA';
			$sign=$this->sign($extraData,$setting['allinpay_rsakey']);
			$extraData['sign']=$sign;
			$extraData=ijson_encode($extraData);
			$query = urlencode("payinfo=".urlencode($extraData));
			$pay_url="alipays://platformapi/startapp?appId=2021001104615521&page=pages/orderDetail/orderDetail&thirdPartSchema=".urlencode($post['returl'])."&query=".$query;
			//file_put_contents(ROOT_D.'/pay_url.txt',$pay_url."~~~\n",FILE_APPEND);
			return $pay_url;
		}else{
			$sign=$this->sign($post,$setting['allinpay_rsakey']);
			//$post['signtype']='RSA';
			$post['sign']=$sign;
			$query=http_build_query($post);
			$pay_url=$url.'?'.$query;
			return $pay_url;
		}
	}
	public function signmd5($params=array(),$secret=''){
		$params['key']=$secret;
		ksort($params);
		$sign_str='';
		foreach($params as $key=>$value){
			if($value || $value=='0'){
				$sign_str.=$key.'='.$value.'&';
			}
		}
		$sign_str=substr($sign_str,0,-1);
		//file_put_contents(ROOT_D.'/2.txt',$sign_str);
		return  strtoupper(md5($sign_str));
	}
	public function check_sign($array=array(),$merchid=0){
		$setting=uni_setting('pay');
		if($merchid){
			$jy_merch=cfc('core')->plugin_exists('jy_merch');
			$jy_merch=plugin('jy_merch')->plugin_setting('setting');
			if($jy_merch['isone_allinpay']){
				$merchset=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'setting');
				$merchset=json_decode($merchset,true);
				if($merchset['allinpay']){
					$setting=$merchset;
				}
			}
		}
		$sign =$array['sign'];
		unset($array['sign']);
		ksort($array);
		$bufSignSrc = $this->ToUrlParams($array);
		$public_key=$setting['allinpay_pubkey'];	
		$public_key = chunk_split($public_key , 64, "\n");
		$key = "-----BEGIN PUBLIC KEY-----\n".$public_key."-----END PUBLIC KEY-----\n";
		$result= openssl_verify($bufSignSrc,base64_decode($sign), $key );
		return $result;
	}
	//RSA签名
	public function sign($array=array(),$private_key=''){
		ksort($array);
		$bufSignSrc = $this->ToUrlParams($array);
		$private_key = chunk_split($private_key , 64, "\n");
		$key = "-----BEGIN RSA PRIVATE KEY-----\n".wordwrap($private_key)."-----END RSA PRIVATE KEY-----";
		if(openssl_sign($bufSignSrc, $signature, $key)){
			//echo 'sign success';
		}else{
			echo 'sign fail';
		} 
		$sign = base64_encode($signature);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
		return $sign;
	}
	public function ToUrlParams($array=array()){
		$buff = "";
		foreach ($array as $k => $v){
			if($v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	public function payapplyagree($params=array(),$issms=false,$isgetsms=false){
		$basic=$this->plugin_setting('basic');
		$setting=uni_setting('pay');
		$merchid=$params['merchid'];
		if($merchid){
			$jy_merch=cfc('core')->plugin_exists('jy_merch');
			$jy_merch=plugin('jy_merch')->plugin_setting('setting');
			if($jy_merch['isone_allinpay']){
				$merchset=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'setting');
				$merchset=json_decode($merchset,true);
				if($merchset['allinpay']){
					$setting=$merchset;
				}
			}
		}
		$post = array(
			'cusid'=>$setting['allinpay_cusid'],
			'appid'=>$setting['allinpay_appid'],
			'version'=>'11',
			'reqtime'=>date("Y-m-d" . "\T" . "H:i:s" . "+08:00", time()),
			'randomstr'=>random(32),
			'signtype'=>'RSA',
			'agreeid'=>$params['agreeid'],
			'currency'=>'CNY',
			'reqsn'=>$params['tid']?:$params['reqsn'],
			'amount'=>intval($params['fee']*100).'',
			'subject'=>$params['title']?:$params['subject'],
			'returl'=>custom_url($params['success_url'],true),
			'notifyurl'=>SITEROOT .'addons/jy_allinpay/notify.php',
		);
		if($basic['istest']){
			if($issms){
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/payapplyagree';
			}else{
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/payapplyagree';
			}
		}else{
			if($issms){
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/payapplyagree';
			}else{
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/payapplyagree';
			}
		}
		$sign=$this->sign($post,$setting['allinpay_rsakey']);
		$post['sign']=$sign;
		//file_put_contents(ROOT_D.'/1.txt',$apiurl.ijson_encode($post)."\n",FILE_APPEND);
		$res=cfc('http')->ihttp_request($apiurl,$post);
		if(is_error($res)){			
			$message="访问失败, 错误: {$res['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$res['content']);
		$res=@json_decode($data,true);
		if($res['trxstatus']!='0000' && $res['trxstatus']!='1999'){
			if($issms){
				$msg='申请支付失败！';
			}else{
				$msg='重新获取验证码失败！';
			}
			exi($msg.$res['errmsg'].$res['retmsg'],'error');
		}else{
			$postdata=array(
				'agreeid'=>$params['agreeid'],
				'reqsn'=>$params['tid'],
				'merchid'=>$params['merchid'],
				'fee'=>$params['fee'],
				'amount'=>intval($params['fee']*100).'',
				'subject'=>$params['title']?:$params['subject'],
				'returl'=>$params['success_url'],
				'notifyurl'=>SITEROOT .'addons/jy_allinpay/notify.php',
				'response_data'=>ijson_encode($res),
			);
			$logid=$this->addpaylog($postdata);
			if($res['trxstatus']!='0000'){
				exi('','','jy_allinpay/pay//logid='.$logid);
			}else{
				pdo_update('jy_allinpay_paylog',array('ispay'=>1,'response_data'=>ijson_encode($res)),array('uniacid'=>$_SESSION['uniacid'],'id'=>$logid));
				 //此处模拟微信支付等进行异步支付结果通知~
				$pay_log=pdo_get('core_paylog',array('uniacid' =>$_SESSION['uniacid'],'tid'=>$params['tid']));
				$difee=$pay_log['di_fee'];
				$di_open=$pay_log['di_fee']>0?1:0;
				cfc('pay')->upcredit_notify($pay_log,$di_open,$difee,'union_online');
				exi('支付成功！','',$params['success_url']?:'jy_weishop/order.list/');
			}
		}
        return $res;
	}
	public function payagreeconfirm($params=array(),$issms=0){
		$basic=$this->plugin_setting('basic');
		$setting=uni_setting('pay');
		$merchid=$params['merchid'];
		if($merchid){
			$jy_merch=cfc('core')->plugin_exists('jy_merch');
			$jy_merch=plugin('jy_merch')->plugin_setting('setting');
			if($jy_merch['isone_allinpay']){
				$merchset=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'setting');
				$merchset=json_decode($merchset,true);
				if($merchset['allinpay']){
					$setting=$merchset;
				}
			}
		}
		$post = array(
			'cusid'=>$setting['allinpay_cusid'],
			'appid'=>$setting['allinpay_appid'],
			'version'=>'11',
			'reqtime'=>date("Y-m-d" . "\T" . "H:i:s" . "+08:00", time()),
			'randomstr'=>random(32),
			'signtype'=>'RSA',
			'agreeid'=>$params['agreeid'],
			'smscode'=>$params['smscode'],
			'thpinfo'=>$params['thpinfo'],
		);
		if($issms){
			$post['orderid']=$params['reqsn'];
		}else{
			$post['reqsn']=$params['reqsn'];
		}
		if($basic['istest']){
			if($issms){
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/paysmsagree';
			}else{
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/payagreeconfirm';
			}
		}else{
			if($issms){
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/paysmsagree';
			}else{
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/payagreeconfirm';
			}
		}
		$sign=$this->sign($post,$setting['allinpay_rsakey']);
		$post['sign']=$sign;
		//file_put_contents(ROOT_D.'/1.txt',$apiurl.ijson_encode($post)."\n",FILE_APPEND);
		$res=cfc('http')->ihttp_request($apiurl,$post);
		if(is_error($res)){			
			$message="访问失败, 错误: {$res['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$res['content']);
		$res=@json_decode($data,true);
		//file_put_contents(ROOT_D.'/1.txt','返回：'.ijson_encode($res)."\n",FILE_APPEND);
		if($res['trxstatus']!='0000'){
			exi('确认支付失败！'.$res['errmsg'].$res['retmsg'],'error');
		}
        return $res;
	}
	public function checkinfo($params=array(),$issms=false,$isgetsms=false){
		$basic=$this->plugin_setting('basic');
		$setting=uni_setting('pay');
		$merchid=$params['merchid'];
		if($merchid){
			$jy_merch=cfc('core')->plugin_exists('jy_merch');
			$jy_merch=plugin('jy_merch')->plugin_setting('setting');
			if($jy_merch['isone_allinpay']){
				$merchset=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'setting');
				$merchset=json_decode($merchset,true);
				if($merchset['allinpay']){
					$setting=$merchset;
				}
			}
		}
		$post=array(
			'cusid'=>$setting['allinpay_cusid'],
			'appid'=>$setting['allinpay_appid'],
			'version'=>'11',
			'reqtime'=>date("Y-m-d" . "\T" . "H:i:s" . "+08:00", time()),
			'randomstr'=>random(32),
			'signtype'=>'RSA',
			'meruserid'=>'meruserid'.$_SESSION['uniacid'],
			'accttype'=>'00',
			'acctno'=>$params['acctno'],
			'idtype'=>'0',
			'idno'=>$params['cardnum'],
			'acctname'=>$params['realname'],
			'mobile'=>$params['mobile'],
		);
		if($issms){
			$post['smscode']=$basic['istest']?'111111':$params['smscode'];
			$post['thpinfo']=$params['thpinfo'];
		}
		if($isgetsms){
			$post['thpinfo']=$params['thpinfo'];
		}
		if($basic['istest']){
			if($issms){
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/agreeconfirm';
			}else{
				$apiurl='https://syb-test.allinpay.com/apiweb/qpay/agreeapply';
			}
		}else{
			if($issms){
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/agreeconfirm';
			}else{
				$apiurl='https://vsp.allinpay.com/apiweb/qpay/agreeapply';
			}
		}
		$sign=$this->sign($post,$setting['allinpay_rsakey']);
		$post['sign']=$sign;
		//file_put_contents(ROOT_D.'/1.txt',$apiurl.ijson_encode($post)."\n",FILE_APPEND);
		$res=cfc('http')->ihttp_request($apiurl,$post);
		if(is_error($res)){			
			$message="访问失败, 错误: {$res['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$res['content']);
		$res=@json_decode($data,true);
		//file_put_contents(ROOT_D.'/1.txt','返回：'.ijson_encode($res)."\n",FILE_APPEND);
		if($res['trxstatus']!='0000' && $res['trxstatus']!='1999'){
			if($isgetsms){
				$msg='获取短信失败！';
			}elseif($issms){
				$msg='确认签约失败！';
			}else{
				$msg='申请签约失败！';
			}
			exi($msg.$res['errmsg'].$res['retmsg'],'error');
		}
        return $res;
    }
	public function check_qianyue($mid=0,$ismobile=0){
		$mid=$mid?:$_SESSION['uid'];
		if($ismobile){
			$mobile=pdo_getcolumn('core_members',array('id'=>$mid,'uniacid'=>$_SESSION['uniacid']),'mobile');
			$item=pdo_get('jy_allinpay_log',array('passed'=>1,'mobile'=>$mobile,'uniacid'=>$_SESSION['uniacid']));
			if(!$item){
				$item=pdo_get('jy_allinpay_log',array('passed'=>2,'mobile'=>$mobile,'uniacid'=>$_SESSION['uniacid']));	
			}
		}
		if(!$item){
			$item=pdo_get('jy_allinpay_log',array('passed'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));	
		}
		if(!$item){
			$item=pdo_get('jy_allinpay_log',array('passed'=>2,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));	
		}
		if(!$item){
			$item=pdo_get('jy_allinpay_log',array('passed'=>0,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));	
		}
		return $item;
	}
	public function addlog($postdata=array()){
		$log=$this->pdo_get('log',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']));
		$data=array(
			'sn'=>'SN'.get_ordersn($this->tablename('log'),'sn'),
			'realname'=>$postdata['realname'],
			'cardnum'=>$postdata['cardnum'],
			'mobile'=>$postdata['mobile'],
			'acctno'=>$postdata['acctno'],
			'meruserid'=>'meruserid'.$_SESSION['uniacid'],
			'accttype'=>'00',
			'type'=>$postdata['type'],
			'passed'=>$postdata['passed']?:0,
			'merchid'=>$postdata['merchid'],
		);
		if($postdata['tid']){
			$success_url=pdo_getcolumn('core_paylog',array('uniacid'=>$_SESSION['uniacid'],'tid'=>$postdata['tid']),'success_url');
			$data['tid']=$postdata['tid'];
			$data['returl']=$success_url;
		}
		if($log['id']){
			$this->pdo_update('log',$data,array('uniacid'=>$_SESSION['uniacid'],'id'=>$log['id']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['mid']=$_SESSION['uid'];
			$data['createtime']=TIMESTAMP;
			$this->pdo_insert('log',$data);
			$log['id']=pdo_insertid();
		}
		return $log['id'];
	}
	public function addpaylog($postdata=array()){
		$log=$this->pdo_get('paylog',array('uniacid'=>$_SESSION['uniacid'],'reqsn'=>$postdata['reqsn']));
		$data=$postdata;
		if($log['id']){
			$this->pdo_update('paylog',$data,array('uniacid'=>$_SESSION['uniacid'],'id'=>$log['id']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['mid']=$_SESSION['uid'];
			$data['createtime']=TIMESTAMP;
			$this->pdo_insert('paylog',$data);
			$log['id']=pdo_insertid();
		}
		return $log['id'];
	}
}
?>